package src.main.其他模式.拦截过滤器模式;

import java.util.ArrayList;
import java.util.List;

public class InterceptingFilterDemo {
    public static void main(String[] args) {
        FilterManager filterManager = new FilterManager(new Target());
        filterManager.setFilter(new AuthenticationFilter());
        filterManager.setFilter(new DebugFilter());

        Client client = new Client();
        client.setFilterManager(filterManager);
        client.sendRequest("localhost");
    }
}
/**过滤器接口*/
interface Filter { void execute(String request);}
/**实体过滤器*/
class AuthenticationFilter implements Filter {
    public void execute(String request){
        System.out.println("Authenticating request: " + request);
    }
}
/**实体过滤器*/
class DebugFilter implements Filter {
    public void execute(String request){
        System.out.println("request log: " + request);
    }
}
/**执行类*/
class Target {
    public void execute(String request){
        System.out.println("Executing request: " + request);
    }
}
/**过滤器链，统一处理单个过滤器*/
class FilterChain {
    private List<Filter> filters = new ArrayList<Filter>();
    private Target target;

    public void addFilter(Filter filter){
        filters.add(filter);
    }

    public void execute(String request){
        for (Filter filter : filters) {
            filter.execute(request);
        }
        target.execute(request);
    }

    public void setTarget(Target target){
        this.target = target;
    }
}
/**筛选器管理器*/
class FilterManager {
    FilterChain filterChain;

    public FilterManager(Target target){
        filterChain = new FilterChain();
        filterChain.setTarget(target);
    }
    public void setFilter(Filter filter){
        filterChain.addFilter(filter);
    }
    public void filterRequest(String request){
        filterChain.execute(request);
    }
}

class Client {
    FilterManager filterManager;
    public void setFilterManager(FilterManager filterManager){
        this.filterManager = filterManager;
    }
    public void sendRequest(String request){
        filterManager.filterRequest(request);
    }
}
